package com.zhy.generator.codegen.mybatis.javaservice;

import com.zhy.generator.codegen.api.CommentGenerator;
import com.zhy.generator.codegen.dom.java.CompilationUnit;
import com.zhy.generator.codegen.dom.java.FullyQualifiedJavaType;
import com.zhy.generator.codegen.dom.java.JavaVisibility;
import com.zhy.generator.codegen.dom.java.TopLevelClass;
import com.zhy.generator.codegen.mybatis.AbstractJavaGenerator;
import com.zhy.generator.config.ConfigurationConstant;
import com.zhy.generator.config.PropertyRegistry;

import java.util.ArrayList;
import java.util.List;

import static cn.hutool.core.util.StrUtil.isBlank;
import static com.zhy.generator.codegen.util.Messages.getString;
import static com.zhy.generator.codegen.util.StringUtility.stringHasValue;

/**
 * @author 源
 */
public class JavaServiceGenerator extends AbstractJavaGenerator {

    @Override
    public List<CompilationUnit> getCompilationUnits() {

        progressCallback.startTask(getString("Progress.12", introspectedTable.getFullyQualifiedTable().toString()));

        CommentGenerator commentGenerator = context.getCommentGenerator();

        String domainObjectName = introspectedTable.getDomainObjectName();

        FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getServiceType());
        TopLevelClass topLevelClass = new TopLevelClass(type);
        topLevelClass.setVisibility(JavaVisibility.PUBLIC);
        commentGenerator.addJavaFileComment(topLevelClass);

        String rootClass = introspectedTable.getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_CLASS);
        if (isBlank(rootClass)) {
            rootClass = context.getConfiguration(ConfigurationConstant.CONFIGURATION_SERVICE).getRootClass();
        }

        if (stringHasValue(rootClass)) {

            FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(rootClass);
            //范型类
            FullyQualifiedJavaType basetype = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
            topLevelClass.addImportedType(basetype);
            fqjt.addTypeArgument(basetype);

            //继承接口类
            topLevelClass.setSuperClass(fqjt);
            topLevelClass.addImportedType(fqjt);
        }
        topLevelClass.addImportedType(new FullyQualifiedJavaType("org.springframework.stereotype.Service")); //$NON-NLS-1$
        topLevelClass.addAnnotation("@Service");

        //serialVersionUID
        addSerialVersionUIDField(topLevelClass);

        //扩展
        List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
        answer.add(topLevelClass);

        List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits();
        if (extraCompilationUnits != null) {
            answer.addAll(extraCompilationUnits);
        }

        return answer;
    }

    public List<CompilationUnit> getExtraCompilationUnits() {
        return null;
    }
}
